import puppeteer from 'puppeteer-extra';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
import type { Browser, ElementHandle } from 'puppeteer-core';
import { dialog, app, BrowserWindow } from 'electron';
import * as path from 'path';
import * as fs from 'fs';
import { EventEmitter } from 'events';
import * as http from 'http';
import * as net from 'net';
import * as url from 'url';
import { BrowserConfig, BrowserInstance, BrowserStatus } from './types';
import { withTimeout, getChromePath, cleanUserDataDirectory, validateBrowserConfig } from './utils';
import { CookieManager, Cookie } from './cookieManager';
import { apiClient } from './apiClient';
import AnonymizeUAPlugin from 'puppeteer-extra-plugin-anonymize-ua';
puppeteer.use(AnonymizeUAPlugin());

// HTTP代理服务器管理类
class HttpProxyServer {
  private server: http.Server | null = null;
  private port: number;
  private socksConfig: any;

  constructor(port: number, socksConfig: any) {
    this.port = port;
    this.socksConfig = socksConfig;
  }

  async start(): Promise<void> {
    return new Promise((resolve, reject) => {
      this.server = http.createServer();
      
      // 处理HTTP请求
      this.server.on('request', (req, res) => this.handleHttpRequest(req, res));
      
      // 处理HTTPS CONNECT请求
      this.server.on('connect', (req, clientSocket, head) => this.handleConnectRequest(req, clientSocket as net.Socket, head));
      
      this.server.listen(this.port, '127.0.0.1', () => {
        console.log(`HTTP代理服务器已启动: 127.0.0.1:${this.port}`);
        resolve();
      });
      
      this.server.on('error', (error) => {
        console.error(`HTTP代理服务器启动失败: ${error.message}`);
        reject(error);
      });
    });
  }

  private handleHttpRequest(req: http.IncomingMessage, res: http.ServerResponse) {
    let targetUrl: string;
    if (req.url && (req.url.startsWith('http://') || req.url.startsWith('https://'))) {
      targetUrl = req.url;
    } else {
      const host = req.headers.host;
      if (!host) {
        res.writeHead(400, { 'Content-Type': 'text/plain' });
        res.end('缺少Host头');
        return;
      }
      // 根据目标网站的实际协议来决定
      // 如果浏览器发送的是相对路径，我们需要判断目标网站是否支持HTTPS
      // 这里我们默认使用HTTPS，如果失败再回退到HTTP
      targetUrl = `https://${host}${req.url || ''}`;
    }
    
    const parsedUrl = url.parse(targetUrl);
    const destHost = parsedUrl.hostname;
    const destPort = parsedUrl.port ? parseInt(parsedUrl.port) : (parsedUrl.protocol === 'https:' ? 443 : 80);

    // 通过SOCKS代理建立到目标的socket
    this.createSocksConnection(destHost!, destPort).then(socket => {
      // 构建HTTP请求
      const requestLine = `${req.method} ${parsedUrl.path} HTTP/1.1\r\n`;
      const headers = Object.keys(req.headers)
        .map(key => `${key}: ${req.headers[key]}`)
        .join('\r\n');
      const httpRequest = requestLine + headers + '\r\n\r\n';
      
      socket.write(httpRequest);
      
      if (req.method !== 'GET' && req.method !== 'HEAD') {
        req.pipe(socket as any);
      }
      
      // 处理响应
      socket.pipe(res);
      
      socket.on('error', (err) => {
        if (!res.headersSent) {
          res.writeHead(500, { 'Content-Type': 'text/plain' });
          res.end('SOCKS代理连接错误: ' + err.message);
        }
      });
      
      res.on('close', () => socket.destroy());
    }).catch(err => {
      // 如果HTTPS连接失败，尝试HTTP
      if (parsedUrl.protocol === 'https:' && !req.url?.startsWith('https://')) {
        const httpUrl = `http://${destHost}${parsedUrl.path}`;
        console.debug(`HTTPS failed, trying HTTP: ${httpUrl}`);
        
        const httpParsedUrl = url.parse(httpUrl);
        const httpDestPort = httpParsedUrl.port ? parseInt(httpParsedUrl.port) : 80;
        
        this.createSocksConnection(destHost!, httpDestPort).then(socket => {
          const requestLine = `${req.method} ${httpParsedUrl.path} HTTP/1.1\r\n`;
          const headers = Object.keys(req.headers)
            .map(key => `${key}: ${req.headers[key]}`)
            .join('\r\n');
          const httpRequest = requestLine + headers + '\r\n\r\n';
          
          socket.write(httpRequest);
          
          if (req.method !== 'GET' && req.method !== 'HEAD') {
            req.pipe(socket as any);
          }
          
          socket.pipe(res);
          
          socket.on('error', (err) => {
            if (!res.headersSent) {
              res.writeHead(500, { 'Content-Type': 'text/plain' });
              res.end('SOCKS代理连接错误: ' + err.message);
            }
          });
          
          res.on('close', () => socket.destroy());
        }).catch(httpErr => {
          res.writeHead(500, { 'Content-Type': 'text/plain' });
          res.end('SOCKS代理连接失败: ' + httpErr.message);
        });
      } else {
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('SOCKS代理连接失败: ' + err.message);
      }
    });
  }

  private handleConnectRequest(req: http.IncomingMessage, clientSocket: net.Socket, head: Buffer) {
    const [host, port] = req.url!.split(':');
    const destPort = port ? parseInt(port) : 443;
    
    // 通过SOCKS代理建立到目标的socket
    this.createSocksConnection(host, destPort).then(socket => {
      clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
      
      // 双向转发
      socket.write(head);
      clientSocket.pipe(socket as any);
      socket.pipe(clientSocket);
      
      socket.on('error', () => clientSocket.destroy());
      clientSocket.on('error', () => socket.destroy());
    }).catch(err => {
      clientSocket.write('HTTP/1.1 500 Connection Error\r\n\r\n');
      clientSocket.destroy();
    });
  }

  private createSocksConnection(host: string, port: number): Promise<net.Socket> {
    return new Promise((resolve, reject) => {
      const socket = new net.Socket();
      
      // 连接到SOCKS代理服务器
      socket.connect(this.socksConfig.port, this.socksConfig.host, () => {
        if (this.socksConfig.type === 'socks5') {
          this.performSocks5Handshake(socket, host, port, resolve, reject);
        } else if (this.socksConfig.type === 'socks4') {
          this.performSocks4Handshake(socket, host, port, resolve, reject);
        } else {
          reject(new Error('不支持的SOCKS类型'));
        }
      });
      
      socket.on('error', reject);
    });
  }

  private performSocks5Handshake(socket: net.Socket, host: string, port: number, resolve: (socket: net.Socket) => void, reject: (error: Error) => void) {
    // SOCKS5 认证方法协商
    const authMethods = [0x00]; // 无认证
    if (this.socksConfig.username && this.socksConfig.password) {
      authMethods.push(0x02); // 用户名密码认证
    }
    
    const authBuffer = Buffer.alloc(2 + authMethods.length);
    authBuffer[0] = 0x05; // SOCKS版本5
    authBuffer[1] = authMethods.length; // 认证方法数量
    authMethods.forEach((method, index) => {
      authBuffer[2 + index] = method;
    });
    
    socket.write(authBuffer);
    
    socket.once('data', (data: Buffer) => {
      if (data.length >= 2 && data[0] === 0x05) {
        const chosenMethod = data[1];
        
        if (chosenMethod === 0x00) {
          // 无认证，直接发送连接请求
          this.sendSocks5ConnectRequest(socket, host, port, resolve, reject);
        } else if (chosenMethod === 0x02) {
          // 用户名密码认证
          this.performSocks5UserPassAuth(socket, host, port, resolve, reject);
        } else {
          reject(new Error('SOCKS5代理不支持指定的认证方法'));
        }
      } else {
        reject(new Error('SOCKS5代理响应格式错误'));
      }
    });
  }

  private performSocks5UserPassAuth(socket: net.Socket, host: string, port: number, resolve: (socket: net.Socket) => void, reject: (error: Error) => void) {
    const username = Buffer.from(this.socksConfig.username, 'utf8');
    const password = Buffer.from(this.socksConfig.password, 'utf8');
    
    const authBuffer = Buffer.alloc(3 + username.length + password.length);
    authBuffer[0] = 0x01; // 认证子协议版本
    authBuffer[1] = username.length; // 用户名长度
    username.copy(authBuffer, 2); // 用户名
    authBuffer[2 + username.length] = password.length; // 密码长度
    password.copy(authBuffer, 3 + username.length); // 密码
    
    socket.write(authBuffer);
    
    socket.once('data', (data: Buffer) => {
      if (data.length >= 2 && data[0] === 0x01) {
        const authStatus = data[1];
        
        if (authStatus === 0x00) {
          // 认证成功，发送连接请求
          this.sendSocks5ConnectRequest(socket, host, port, resolve, reject);
        } else {
          reject(new Error('SOCKS5代理认证失败'));
        }
      } else {
        reject(new Error('SOCKS5代理认证响应格式错误'));
      }
    });
  }

  private sendSocks5ConnectRequest(socket: net.Socket, host: string, port: number, resolve: (socket: net.Socket) => void, reject: (error: Error) => void) {
    const hostBuffer = Buffer.from(host, 'utf8');
    const requestBuffer = Buffer.alloc(7 + hostBuffer.length);
    
    requestBuffer[0] = 0x05; // SOCKS版本5
    requestBuffer[1] = 0x01; // CONNECT命令
    requestBuffer[2] = 0x00; // 保留字段
    requestBuffer[3] = 0x03; // 域名类型
    requestBuffer[4] = hostBuffer.length; // 域名长度
    hostBuffer.copy(requestBuffer, 5); // 域名
    requestBuffer.writeUInt16BE(port, 5 + hostBuffer.length); // 端口
    
    socket.write(requestBuffer);
    
    socket.once('data', (data: Buffer) => {
      if (data.length >= 4 && data[0] === 0x05) {
        const reply = data[1];
        
        if (reply === 0x00) {
          resolve(socket);
        } else {
          reject(new Error(`SOCKS5代理连接失败，错误码: ${reply}`));
        }
      } else {
        reject(new Error('SOCKS5代理响应格式错误'));
      }
    });
  }

  private performSocks4Handshake(socket: net.Socket, host: string, port: number, resolve: (socket: net.Socket) => void, reject: (error: Error) => void) {
    // SOCKS4 简单连接请求
    const hostBuffer = Buffer.from(host, 'utf8');
    const requestBuffer = Buffer.alloc(9 + hostBuffer.length);
    
    requestBuffer[0] = 0x04; // SOCKS版本4
    requestBuffer[1] = 0x01; // CONNECT命令
    requestBuffer.writeUInt16BE(port, 2); // 端口
    requestBuffer.writeUInt32BE(0, 4); // IP地址 (0.0.0.0 for domain)
    requestBuffer[8] = 0x00; // 用户名结束符
    hostBuffer.copy(requestBuffer, 9); // 域名
    requestBuffer[9 + hostBuffer.length] = 0x00; // 域名结束符
    
    socket.write(requestBuffer);
    
    socket.once('data', (data: Buffer) => {
      if (data.length >= 8 && data[0] === 0x00) {
        const reply = data[1];
        
        if (reply === 0x5A) {
          resolve(socket);
        } else {
          reject(new Error(`SOCKS4代理连接失败，错误码: ${reply}`));
        }
      } else {
        reject(new Error('SOCKS4代理响应格式错误'));
      }
    });
  }

  stop(): void {
    if (this.server) {
      this.server.close();
      this.server = null;
      console.log(`HTTP代理服务器已停止: 127.0.0.1:${this.port}`);
    }
  }

  getPort(): number {
    return this.port;
  }
}

class BrowserManager extends EventEmitter {
  private instances: Map<string, BrowserInstance> = new Map();
  private proxyServers: Map<string, HttpProxyServer> = new Map();
  private isShuttingDown = false;
  private readonly userDataBasePath: string;
  private statusCheckInterval: NodeJS.Timeout | null = null;
  private nextProxyPort = 8888; // 起始代理端口
  
  // 全局状态管理 - 简化逻辑
  private globalBrowserStatuses: Map<string, BrowserStatus> = new Map();

  // Cookie 监控相关
  private cookieMonitorIntervals: Map<string, NodeJS.Timeout> = new Map();
  private lastReportedCookies: Map<string, string> = new Map();
  
  // Cookie 监控配置
  private readonly COOKIE_MONITOR_DELAY = 30000; // 延迟30秒启动监控
  private readonly COOKIE_MONITOR_INTERVAL = 5000; // 每5秒检查一次

  constructor() {
    super();
    console.log('BrowserManager initialized - Testing hot reload');
    this.testHotReload();
    
    // 用户数据目录放在项目根目录下
    this.userDataBasePath = process.env.NODE_ENV === 'development'
      ? path.join(__dirname, '../../browser-instances')
      : path.join(process.resourcesPath, 'browser-instances');
    
    console.log(`User data directory: ${this.userDataBasePath}`);
    
    this.ensureUserDataDirectory();
    this.startStatusCheck();

    // 监听应用退出事件
    app.on('before-quit', async (event) => {
      // 如果正在关闭,阻止退出
      if (this.isShuttingDown) {
        event.preventDefault();
        return;
      }

      // 标记正在关闭
      this.isShuttingDown = true;
      event.preventDefault();

      console.log('Cleaning up before quit...');
      
      // 停止状态检查
      if (this.statusCheckInterval) {
        clearInterval(this.statusCheckInterval);
        this.statusCheckInterval = null;
      }

      try {
        // 停止所有浏览器实例
        await this.stopAllBrowsers();
        
        console.log('Cleanup completed, quitting app...');
        app.quit();
      } catch (error) {
        console.error('Failed to cleanup:', error);
        this.isShuttingDown = false;
        dialog.showErrorBox('清理失败', '应用退出时清理资源失败，请手动结束进程。');
      }
    });

    // 开发环境下的额外处理
    if (process.env.NODE_ENV === 'development') {
      // 监听文件变化导致的重启
      process.on('SIGTERM', async () => {
        console.log('Received SIGTERM, cleaning up...');
        await this.stopAllBrowsers();
      });
    }
  }

  private startStatusCheck() {
    if (this.statusCheckInterval) {
      clearInterval(this.statusCheckInterval);
    }
    this.statusCheckInterval = setInterval(() => this.checkAllInstancesStatus(), 200); // 缩短到200ms，更及时
  }

  private async checkAllInstancesStatus() {
    // 简化状态检查：只检查全局状态中的浏览器
    for (const [id, status] of this.globalBrowserStatuses) {
      try {
        // 如果状态正在处理中，跳过检查
        if (status.inProgress) {
          continue;
        }
        
        // 检查实例是否存在
        const instance = this.instances.get(id);
        if (!instance || !instance.browser) {
          // 实例不存在，但全局状态显示运行中，更新为已停止
          if (status.isRunning) {
            console.debug(`Status check: Browser ${id} instance not found, setting to stopped`);
            this.setBrowserStatus(id, {
              isRunning: false,
              lastChecked: Date.now(),
              inProgress: false
            });
          }
          continue;
        }
        
        // 检查浏览器是否真的在运行
        const isRunning = await this.checkBrowserRunning(instance.browser);
        if (isRunning !== status.isRunning) {
          console.debug(`Status check: Browser ${id} running state changed from ${status.isRunning} to ${isRunning}`);
          this.setBrowserStatus(id, {
            isRunning,
            lastChecked: Date.now(),
            inProgress: false
          });
        } else {
          // 更新最后检查时间
          this.setBrowserStatus(id, {
            isRunning: status.isRunning,
            lastChecked: Date.now(),
            inProgress: false
          });
        }
      } catch (error) {
        console.debug(`Status check error for browser ${id}:`, error);
        this.setBrowserStatus(id, {
          isRunning: false,
          lastChecked: Date.now(),
          inProgress: false
        });
      }
    }
  }

  private async checkBrowserRunning(browser: Browser): Promise<boolean> {
    if (!browser) {
      console.debug('Browser is null or undefined');
      return false;
    }

    try {
      // 1. 检查连接状态
      if (!browser.isConnected()) {
        console.debug('Browser not connected');
        return false;
      }
      
      // 2. 检查进程状态
      const process = browser.process();
      if (!process || process.killed) {
        console.debug('Browser process not found or killed');
        return false;
      }

      // 3. 检查页面和目标
      try {
        const pages = await withTimeout(browser.pages())

        const targets = await browser.targets();

        if (!pages || pages.length === 0) {
          console.debug('No pages found');
          // return false;
        }

        if (!targets || targets.length === 0) {
          console.debug('No targets found');
          return false;
        }

        return true;
      } catch (error) {
        console.debug('Failed to check pages/targets:', error);
        return false;
      }
    } catch (error) {
      console.debug('Failed to check browser status:', error);
      return false;
    }
  }

  // 删除不再需要的 updateInstanceStatus 方法，统一使用 setBrowserStatus

  private ensureUserDataDirectory() {
    if (!fs.existsSync(this.userDataBasePath)) {
      fs.mkdirSync(this.userDataBasePath, { recursive: true });
    }
  }



  private getUserDataPath(id: string): string {
    return path.join(this.userDataBasePath, id);
  }

  private async cleanupInstance(id: string) {
    console.log(`Cleaning up instance ${id}...`);
    const instance = this.instances.get(id);
    if (!instance) return;

    try {
      // 停止 cookie 监控
      this.stopCookieMonitoring(id);
      
      if (instance.browser) {
        // 设置清理超时
        const cleanupTimeout = setTimeout(() => {
          console.log(`Cleanup timeout for instance ${id}, forcing close...`);
          try {
            instance.browser.process()?.kill();
          } catch (error) {
            console.error(`Failed to kill browser process ${id}:`, error);
          }
        }, 1000);

        try {
          // 关闭所有页面
          const pages = await instance.browser.pages().catch(() => []);
          await Promise.all(pages.map(page => page.close().catch(() => {})));
          
          // 关闭浏览器
          await instance.browser.close();
          
          clearTimeout(cleanupTimeout);
        } catch (error) {
          console.error(`Error closing browser ${id}:`, error);
          // 如果正常关闭失败，强制结束进程
          try {
            instance.browser.process()?.kill();
          } catch (e) {
            console.error(`Failed to kill browser process ${id}:`, e);
          }
        }
      }
    } catch (error) {
      console.error(`Failed to cleanup browser instance ${id}:`, error);
    } finally {
      // 停止HTTP代理服务器
      this.stopHttpProxyServer(id);
      
      // 清理文件系统
      try {
        const userDataDir = this.getUserDataPath(id);
        cleanUserDataDirectory(userDataDir);
      } catch (error) {
        console.error(`Failed to clean user data directory for ${id}:`, error);
      }

      // 更新全局状态为已停止
      this.setBrowserStatus(id, {
        isRunning: false,
        lastChecked: Date.now(),
        inProgress: false
      });
      console.debug(`Instance ${id} status updated to stopped after cleanup`);
    }
  }

  private handleBrowserDisconnect(id: string) {
    if (!this.isShuttingDown) {
      console.log(`Browser instance ${id} disconnected unexpectedly`);
    }
  }



  isInstanceRunning(id: string): boolean {
    return this.instances.get(id)?.status.isRunning || false;
  }

  async launchBrowser(config: BrowserConfig & { googleAuto?: boolean; googleKeyword?: string; googleDomain?: string; }) {
    console.debug(`Attempting to launch browser for config: ${config.id}`);

    // 1. 前置检查
    if (this.isShuttingDown) {
      throw new Error('应用正在关闭，无法启动新的浏览器实例');
    }

    // 检查是否已存在实例
    const existingInstance = this.instances.get(config.id);
    if (existingInstance) {
      // 检查browser对象是否真的还活着
      let reallyRunning = false;
      try {
        reallyRunning = await this.checkBrowserRunning(existingInstance.browser);
      } catch {}
      if (!reallyRunning) {
        // 僵尸实例，强制清理
        console.warn(`Found zombie instance for ${config.id}, force cleanup.`);
        await this.cleanupInstance(config.id);
        this.instances.delete(config.id);
        this.setBrowserStatus(config.id, {
          isRunning: false,
          lastChecked: Date.now(),
          inProgress: false
        });
      } else if (existingInstance.status.isRunning || existingInstance.status.inProgress) {
        throw new Error('浏览器实例已存在且正在运行');
      } else {
        // 已停止但未清理
        this.instances.delete(config.id);
      }
    }

    // 不再需要本地配置缓存，直接使用传入的配置

    // 2. 准备实例
    const userDataDir = this.getUserDataPath(config.id);
    console.debug(`Using user data directory: ${userDataDir}`);

    const instance: BrowserInstance = {
      id: config.id,
      browser: null as any,
      config,
      status: {
        isRunning: false,
        lastChecked: Date.now(),
        inProgress: true,
        action: 'starting'
      }
    };

    this.instances.set(config.id, instance);
    // 设置全局状态
    this.setBrowserStatus(config.id, {
      isRunning: false,
      lastChecked: Date.now(),
      inProgress: true,
      action: 'starting'
    });

    try {
      // 3. 准备用户数据目录
      if (!fs.existsSync(userDataDir)) {
        console.debug(`Creating user data directory: ${userDataDir}`);
        fs.mkdirSync(userDataDir, { recursive: true });
      } else {
        console.debug(`Cleaning existing user data directory: ${userDataDir}`);
        cleanUserDataDirectory(userDataDir);
      }

      // 4. 启动HTTP代理服务器（仅对SOCKS代理）
      let httpProxyPort: number | null = null;
      if (config.proxy && config.proxy.enabled && (config.proxy.type === 'socks4' || config.proxy.type === 'socks5')) {
        try {
          httpProxyPort = await this.startHttpProxyServer(config);
          console.debug(`HTTP代理服务器已启动: 127.0.0.1:${httpProxyPort}`);
        } catch (error) {
          console.error(`Failed to start HTTP proxy server for ${config.id}:`, error);
          throw new Error(`启动HTTP代理服务器失败: ${error instanceof Error ? error.message : '未知错误'}`);
        }
      }

      // 5. 启动浏览器
      console.debug(`Launching browser with Puppeteer`);
      const chromePath = getChromePath();
      console.info(`Chrome executable path: ${chromePath}`);
      
      // 验证Chrome路径
      if (!fs.existsSync(chromePath)) {
        throw new Error(`Chrome executable not found at: ${chromePath}`);
      }

      let browser: Browser;
      try {
        const args = [
          '--fingerprint-brand-version=112',
          '--fingerprint-brand=Opera',
          '--disable-backgrounding-occluded-windows', // 禁用窗口遮挡时的后台处理
          '--disable-breakpad', // 禁用崩溃报告
          '--disable-component-extensions-with-background-pages', // 禁用带后台页面的组件扩展
          '--disable-features=TranslateUI', // 禁用翻译提示
          '--disable-renderer-backgrounding', // 禁用渲染器后台处理
          '--autoplay-policy=user-gesture-required', // 要求用户手势才能自动播放
          '--disable-client-side-phishing-detection', // 禁用客户端钓鱼检测
          '--disable-sync', // 禁用Chrome同步功能
          '--no-default-browser-check', // 禁用默认浏览器检查
          '--window-size=1280,720', // 设置默认窗口大小
          '--window-position=50,50', // 设置初始窗口位置
        ];

        // 添加 user agent 参数
        if (config.userAgent) {
          args.push(`--user-agent=${config.userAgent}`);
        }

        // 添加代理配置
        if (config.proxy && config.proxy.enabled) {
          if (config.proxy.type === 'http' || config.proxy.type === 'https') {
            // 直接使用HTTP/HTTPS代理
            console.debug(`Configuring direct HTTP proxy: ${config.proxy.type}://${config.proxy.host}:${config.proxy.port}`);
            
            let proxyUrl: string;
            if (config.proxy.username && config.proxy.password) {
              proxyUrl = `${config.proxy.type}://${config.proxy.username}:${config.proxy.password}@${config.proxy.host}:${config.proxy.port}`;
            } else {
              proxyUrl = `${config.proxy.type}://${config.proxy.host}:${config.proxy.port}`;
            }
            
            args.push(`--proxy-server=${proxyUrl}`);
            
            // 添加代理相关的高级参数
            args.push('--proxy-bypass-list=<-loopback>'); // 绕过本地地址
            args.push('--disable-background-timer-throttling'); // 禁用后台定时器限制
          } else if (httpProxyPort) {
            // 使用HTTP代理服务器转发SOCKS代理
            console.debug(`Configuring HTTP proxy server: 127.0.0.1:${httpProxyPort}`);
            args.push(`--proxy-server=127.0.0.1:${httpProxyPort}`);
            
            // 添加代理相关的高级参数
            args.push('--proxy-bypass-list=<-loopback>'); // 绕过本地地址
            args.push('--disable-background-timer-throttling'); // 禁用后台定时器限制
          }
        }

        browser = await puppeteer.launch({
          executablePath: chromePath,
          userDataDir,
          headless: false,
          defaultViewport: null, // 让窗口大小由操作系统/用户决定
          args: args,
          ignoreDefaultArgs: ['--enable-automation'], // 隐藏自动化提示
        });

        if (!browser) {
          throw new Error('Browser launch returned null');
        }

        console.debug('Browser launched successfully');
      } catch (error) {
        console.error('Failed to launch browser:', error);
        throw new Error(
          error instanceof Error 
            ? `启动浏览器失败: ${error.message}` 
            : '启动浏览器失败'
        );
      }

      // 6. 设置实例
      instance.browser = browser;
      console.debug(`Browser launched, waiting for initialization`);
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 7. 验证启动状态
      console.debug(`Verifying browser status`);
      const isRunning = await this.checkBrowserRunning(browser);
      if (!isRunning) {
        throw new Error('浏览器启动验证失败');
      }

      // 立即推送运行状态，UI立刻切换
      instance.status = {
        isRunning: true,
        lastChecked: Date.now(),
        inProgress: false
      };
      this.setBrowserStatus(instance.id, {
        isRunning: true,
        lastChecked: Date.now(),
        inProgress: false
      });

      // 后续自动化、cookie同步异步进行，不影响UI
      (async () => {
        // 自动化逻辑：如有参数则自动搜索
        if (config.googleAuto && config.googleKeyword && config.googleDomain) {
          try {
            await this.autoGoogleSearch(browser, config.googleKeyword, config.googleDomain);
          } catch (e) {
            console.warn('Google自动化失败:', e);
          }
        }
        // 加载 cookies 并开始监控
        try {
          await this.loadCookiesFromServer(config.id, browser);
          this.startCookieMonitoring(config.id, browser);
        } catch (error) {
          console.warn(`Failed to setup cookie sync for instance ${config.id}:`, error);
        }
      })();

      // 8. 更新状态
      // instance.status = {
      //   isRunning: true,
      //   lastChecked: Date.now(),
      //   inProgress: false
      // };

      // 更新全局状态
      // this.setBrowserStatus(instance.id, {
      //   isRunning: true,
      //   lastChecked: Date.now(),
      //   inProgress: false
      // });
      
      // 10. 设置监听器
      browser.on('disconnected', async () => {
        console.debug(`Browser instance ${config.id} disconnected`);
        
        // 停止 cookie 监控
        this.stopCookieMonitoring(config.id);
        
        // 立即更新全局状态为已停止
        console.debug(`Setting browser ${config.id} status to stopped due to disconnect`);
        this.setBrowserStatus(config.id, {
          isRunning: false,
          lastChecked: Date.now(),
          inProgress: false
        });
        
        // 清理实例
        await this.cleanupInstance(config.id);
        this.instances.delete(config.id);
        // 停止HTTP代理服务器
        this.stopHttpProxyServer(config.id);
      });

      console.debug(`Browser instance ${config.id} successfully launched`);
      return browser;
    } catch (error) {
      // 10. 错误处理
      console.error(`Failed to launch browser instance ${config.id}:`, error);
      
      this.instances.delete(config.id);
      cleanUserDataDirectory(userDataDir);
      // 停止HTTP代理服务器
      this.stopHttpProxyServer(config.id);
      
      // 更新全局状态为启动失败
      this.setBrowserStatus(config.id, {
        isRunning: false,
        lastChecked: Date.now(),
        inProgress: false
      });
      
      if (error instanceof Error) {
        throw new Error(`启动浏览器失败: ${error.message}`);
      } else {
        throw new Error('启动浏览器失败');
      }
    }
  }

  async stopBrowser(id: string) {
    const instance = this.instances.get(id);
    if (!instance) {
      // 如果实例不存在，可能是已经被手动关闭了，直接发送停止状态并彻底清理
      console.log(`Browser instance ${id} not found, assuming it was manually closed`);
      await this.cleanupInstance(id);
      this.instances.delete(id);
      this.setBrowserStatus(id, {
        isRunning: false,
        lastChecked: Date.now(),
        inProgress: false
      });
      return true;
    }

    console.debug(`Stopping browser ${id}`);
    // 设置全局状态为停止中
    this.setBrowserStatus(id, {
      isRunning: false,
      lastChecked: Date.now(),
      inProgress: true,
      action: 'stopping'
    });

    try {
      await this.cleanupInstance(id);
      console.debug(`Browser ${id} stopped successfully`);
      return true;
    } catch (error) {
      console.error(`Failed to stop browser ${id}:`, error);
      // 即使清理失败，也要更新状态为已停止
      this.setBrowserStatus(id, {
        isRunning: false,
        lastChecked: Date.now(),
        inProgress: false
      });
      throw new Error(error instanceof Error ? `关闭浏览器失败: ${error.message}` : '关闭浏览器失败');
    }
  }

  // 导航浏览器到指定URL
  async navigateBrowser(id: string, url: string) {
    const instance = this.instances.get(id);
    if (!instance) {
      throw new Error('找不到浏览器实例');
    }

    if (!instance.browser) {
      throw new Error('浏览器实例未启动');
    }

    try {
      const pages = await instance.browser.pages();
      if (pages.length > 0) {
        // 使用第一个页面导航
        await pages[0].goto(url, { waitUntil: 'networkidle0' });
        return true;
      } else {
        // 如果没有页面，创建新页面
        const page = await instance.browser.newPage();
        await page.goto(url, { waitUntil: 'networkidle0' });
        return true;
      }
    } catch (error) {
      throw new Error(error instanceof Error ? `导航失败: ${error.message}` : '导航失败');
    }
  }

  async stopAllBrowsers() {
    console.log('Stopping all browsers...');
    this.isShuttingDown = true;
    
    if (this.statusCheckInterval) {
      clearInterval(this.statusCheckInterval);
      this.statusCheckInterval = null;
    }

    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error('Cleanup timeout')), 2000);
    });

    try {
      // 并行清理所有实例，但添加超时
      await Promise.race([
        Promise.all(
          Array.from(this.instances.keys()).map(id => 
            this.cleanupInstance(id).catch(error => {
              console.error(`Failed to stop browser ${id}:`, error);
            })
          )
        ),
        timeoutPromise
      ]);
    } catch (error) {
      console.error('Failed to stop all browsers:', error);
    } finally {
      // 确保清理所有资源
      this.instances.clear();
      
      // 停止所有 cookie 监控
      this.cleanupAllCookieMonitoring();
      
      // 停止所有HTTP代理服务器
      for (const [id, proxyServer] of this.proxyServers) {
        try {
          proxyServer.stop();
          console.log(`Stopped HTTP proxy server for ${id}`);
        } catch (error) {
          console.error(`Failed to stop HTTP proxy server for ${id}:`, error);
        }
      }
      this.proxyServers.clear();
      
      this.isShuttingDown = false;
    }
  }

  // 简化的状态管理方法
  private setBrowserStatus(id: string, status: BrowserStatus) {
    const oldStatus = this.globalBrowserStatuses.get(id);
    this.globalBrowserStatuses.set(id, status);
    this.emit('statusUpdate', id, status);
    // 正确推送到所有窗口，确保UI立刻收到
    if (BrowserWindow && BrowserWindow.getAllWindows) {
      BrowserWindow.getAllWindows().forEach(win => {
        if (!win.isDestroyed()) {
          win.webContents.send('browser-status-update', id, status);
        }
      });
    }
  }

  private getGlobalBrowserStatus(id: string): BrowserStatus {
    return this.globalBrowserStatuses.get(id) || {
      isRunning: false,
      lastChecked: Date.now(),
      inProgress: false
    };
  }

  getAllBrowserStatuses(): Map<string, BrowserStatus> {
    return new Map(this.globalBrowserStatuses);
  }

  getBrowserStatus(id: string): BrowserStatus | null {
    return this.globalBrowserStatuses.get(id) || null;
  }

  private testHotReload() {
    console.log('Hot reload test function called at1:', new Date().toISOString());
  }

  // 启动HTTP代理服务器
  private async startHttpProxyServer(config: BrowserConfig): Promise<number> {
    if (!config.proxy || !config.proxy.enabled) {
      throw new Error('代理未启用');
    }

    // 检查是否已经存在代理服务器
    if (this.proxyServers.has(config.id)) {
      const existingServer = this.proxyServers.get(config.id);
      if (existingServer) {
        return existingServer.getPort();
      }
    }

    // 分配新的端口
    const port = this.nextProxyPort++;
    
    // 创建SOCKS配置
    const socksConfig = {
      host: config.proxy.host,
      port: config.proxy.port,
      type: config.proxy.type,
      username: config.proxy.username,
      password: config.proxy.password
    };

    // 创建并启动HTTP代理服务器
    const proxyServer = new HttpProxyServer(port, socksConfig);
    await proxyServer.start();
    
    // 保存代理服务器实例
    this.proxyServers.set(config.id, proxyServer);
    
    console.log(`HTTP代理服务器已启动: 127.0.0.1:${port} -> ${config.proxy.type}://${config.proxy.host}:${config.proxy.port}`);
    
    return port;
  }

  // 停止HTTP代理服务器
  private stopHttpProxyServer(instanceId: string): void {
    const proxyServer = this.proxyServers.get(instanceId);
    if (proxyServer) {
      proxyServer.stop();
      this.proxyServers.delete(instanceId);
      console.log(`HTTP代理服务器已停止: ${instanceId}`);
    }
  }

  // 测试代理连接
  async testProxy(config: BrowserConfig): Promise<{ success: boolean; message: string }> {
    if (!config.proxy || !config.proxy.enabled) {
      return { success: false, message: '代理未启用' };
    }

    try {
      console.log(`Testing proxy: ${config.proxy.type}://${config.proxy.host}:${config.proxy.port}`);
      
      switch (config.proxy.type) {
        case 'http':
        case 'https': {
          return await this.testHttpProxy(config.proxy);
        }
        case 'socks4':
        case 'socks5': {
          return await this.testSocksProxy(config.proxy);
        }
        default:
          return { success: false, message: '不支持的代理类型' };
      }
    } catch (error) {
      console.error('Proxy test failed:', error);
      return { 
        success: false, 
        message: `代理连接失败: ${error instanceof Error ? error.message : '未知错误'}` 
      };
    }
  }

  // 测试HTTP/HTTPS代理
  private async testHttpProxy(proxy: any): Promise<{ success: boolean; message: string }> {
    try {
      const axios = require('axios');
      const httpsProxyAgent = require('https-proxy-agent');
      const httpProxyAgent = require('http-proxy-agent');

      let proxyUrl: string;
      if (proxy.username && proxy.password) {
        proxyUrl = `${proxy.type}://${proxy.username}:${proxy.password}@${proxy.host}:${proxy.port}`;
      } else {
        proxyUrl = `${proxy.type}://${proxy.host}:${proxy.port}`;
      }

      console.log(`Testing HTTP proxy: ${proxyUrl}`);

      const agent = proxy.type === 'https' 
        ? new httpsProxyAgent(proxyUrl)
        : new httpProxyAgent(proxyUrl);

      const response = await axios.get('http://httpbin.org/ip', {
        httpsAgent: agent,
        httpAgent: agent,
        timeout: 10000,
        validateStatus: () => true
      });

      console.log(`HTTP proxy test response status: ${response.status}`);

      if (response.status === 200) {
        return { 
          success: true, 
          message: `HTTP代理连接成功，代理已生效，当前IP: ${response.data.origin}` 
        };
      } else {
        return { 
          success: false, 
          message: `HTTP代理连接失败，状态码: ${response.status}` 
        };
      }
    } catch (error) {
      console.error('HTTP proxy test error:', error);
      return { 
        success: false, 
        message: `HTTP代理连接失败: ${error instanceof Error ? error.message : '未知错误'}` 
      };
    }
  }

  // 测试SOCKS代理
  private async testSocksProxy(proxy: any): Promise<{ success: boolean; message: string }> {
    return new Promise((resolve) => {
      const net = require('net');
      
      // 创建TCP连接测试代理服务器是否可达
      const socket = new net.Socket();
      let connected = false;
      
      // 设置超时
      const timeout = setTimeout(() => {
        if (!connected) {
          socket.destroy();
          resolve({ 
            success: false, 
            message: `SOCKS代理连接超时: ${proxy.host}:${proxy.port}` 
          });
        }
      }, 10000);

      socket.on('connect', () => {
        connected = true;
        clearTimeout(timeout);
        
        // 如果配置了认证信息，尝试进行SOCKS认证
        if (proxy.username && proxy.password) {
          this.performSocksAuth(socket, proxy, resolve);
        } else {
          socket.destroy();
          resolve({ 
            success: true, 
            message: `SOCKS代理服务器可达: ${proxy.host}:${proxy.port} (无需认证)` 
          });
        }
      });

      socket.on('error', (error: any) => {
        clearTimeout(timeout);
        resolve({ 
          success: false, 
          message: `SOCKS代理连接失败: ${error.message}` 
        });
      });

      socket.on('timeout', () => {
        clearTimeout(timeout);
        socket.destroy();
        resolve({ 
          success: false, 
          message: `SOCKS代理连接超时: ${proxy.host}:${proxy.port}` 
        });
      });

      // 尝试连接到代理服务器
      socket.connect(proxy.port, proxy.host);
    });
  }

  // 执行SOCKS认证
  private performSocksAuth(socket: any, proxy: any, resolve: (result: { success: boolean; message: string }) => void) {
    try {
      const socksVersion = proxy.type === 'socks4' ? 4 : 5;
      
      if (socksVersion === 5) {
        // SOCKS5 认证流程
        // 1. 发送认证方法协商
        const authMethods = [0x00]; // 无认证
        if (proxy.username && proxy.password) {
          authMethods.push(0x02); // 用户名密码认证
        }
        
        const authBuffer = Buffer.alloc(2 + authMethods.length);
        authBuffer[0] = 0x05; // SOCKS版本5
        authBuffer[1] = authMethods.length; // 认证方法数量
        authMethods.forEach((method, index) => {
          authBuffer[2 + index] = method;
        });
        
        socket.write(authBuffer);
        
        // 2. 接收服务器响应
        socket.once('data', (data: Buffer) => {
          if (data.length >= 2 && data[0] === 0x05) {
            const chosenMethod = data[1];
            
            if (chosenMethod === 0x00) {
              // 无认证，直接测试连接
              this.testSocks5Connection(socket, proxy, resolve);
            } else if (chosenMethod === 0x02) {
              // 用户名密码认证
              this.performSocks5UserPassAuth(socket, proxy, resolve);
            } else {
              socket.destroy();
              resolve({ 
                success: false, 
                message: `SOCKS5代理不支持指定的认证方法` 
              });
            }
          } else {
            socket.destroy();
            resolve({ 
              success: false, 
              message: `SOCKS5代理响应格式错误` 
            });
          }
        });
      } else {
        // SOCKS4 认证流程
        this.performSocks4Auth(socket, proxy, resolve);
      }
    } catch (error) {
      socket.destroy();
      resolve({ 
        success: false, 
        message: `SOCKS认证失败: ${error instanceof Error ? error.message : '未知错误'}` 
      });
    }
  }

  // SOCKS5 用户名密码认证
  private performSocks5UserPassAuth(socket: any, proxy: any, resolve: (result: { success: boolean; message: string }) => void) {
    try {
      const username = Buffer.from(proxy.username, 'utf8');
      const password = Buffer.from(proxy.password, 'utf8');
      
      const authBuffer = Buffer.alloc(3 + username.length + password.length);
      authBuffer[0] = 0x01; // 认证子协议版本
      authBuffer[1] = username.length; // 用户名长度
      username.copy(authBuffer, 2); // 用户名
      authBuffer[2 + username.length] = password.length; // 密码长度
      password.copy(authBuffer, 3 + username.length); // 密码
      
      socket.write(authBuffer);
      
      socket.once('data', (data: Buffer) => {
        if (data.length >= 2 && data[0] === 0x01) {
          const authStatus = data[1];
          
          if (authStatus === 0x00) {
            // 认证成功，测试连接
            this.testSocks5Connection(socket, proxy, resolve);
          } else {
            socket.destroy();
            resolve({ 
              success: false, 
              message: `SOCKS5代理认证失败，请检查用户名和密码` 
            });
          }
        } else {
          socket.destroy();
          resolve({ 
            success: false, 
            message: `SOCKS5代理认证响应格式错误` 
          });
        }
      });
    } catch (error) {
      socket.destroy();
      resolve({ 
        success: false, 
        message: `SOCKS5认证失败: ${error instanceof Error ? error.message : '未知错误'}` 
      });
    }
  }

  // SOCKS4 认证
  private performSocks4Auth(socket: any, proxy: any, resolve: (result: { success: boolean; message: string }) => void) {
    try {
      // SOCKS4 不支持用户名密码认证，只能测试连接
      this.testSocks4Connection(socket, proxy, resolve);
    } catch (error) {
      socket.destroy();
      resolve({ 
        success: false, 
        message: `SOCKS4连接失败: ${error instanceof Error ? error.message : '未知错误'}` 
      });
    }
  }

  // 测试SOCKS5连接
  private testSocks5Connection(socket: any, proxy: any, resolve: (result: { success: boolean; message: string }) => void) {
    try {
      // 发送连接请求到 httpbin.org
      const targetHost = 'httpbin.org';
      const targetPort = 80;
      
      const hostBuffer = Buffer.from(targetHost, 'utf8');
      const requestBuffer = Buffer.alloc(7 + hostBuffer.length);
      
      requestBuffer[0] = 0x05; // SOCKS版本5
      requestBuffer[1] = 0x01; // CONNECT命令
      requestBuffer[2] = 0x00; // 保留字段
      requestBuffer[3] = 0x03; // 域名类型
      requestBuffer[4] = hostBuffer.length; // 域名长度
      hostBuffer.copy(requestBuffer, 5); // 域名
      requestBuffer.writeUInt16BE(targetPort, 5 + hostBuffer.length); // 端口
      
      socket.write(requestBuffer);
      
      socket.once('data', (data: Buffer) => {
        if (data.length >= 4 && data[0] === 0x05) {
          const reply = data[1];
          
          if (reply === 0x00) {
            socket.destroy();
            resolve({ 
              success: true, 
              message: `SOCKS5代理连接成功，代理已生效: ${proxy.host}:${proxy.port}` 
            });
          } else {
            socket.destroy();
            resolve({ 
              success: false, 
              message: `SOCKS5代理连接失败，错误码: ${reply}` 
            });
          }
        } else {
          socket.destroy();
          resolve({ 
            success: false, 
            message: `SOCKS5代理响应格式错误` 
          });
        }
      });
    } catch (error) {
      socket.destroy();
      resolve({ 
        success: false, 
        message: `SOCKS5连接测试失败: ${error instanceof Error ? error.message : '未知错误'}` 
      });
    }
  }

  // 测试SOCKS4连接
  private testSocks4Connection(socket: any, proxy: any, resolve: (result: { success: boolean; message: string }) => void) {
    try {
      // SOCKS4 简单连接测试
      socket.destroy();
      resolve({ 
        success: true, 
        message: `SOCKS4代理连接成功，代理已生效: ${proxy.host}:${proxy.port}` 
      });
    } catch (error) {
      socket.destroy();
      resolve({ 
        success: false, 
        message: `SOCKS4连接测试失败: ${error instanceof Error ? error.message : '未知错误'}` 
      });
    }
  }

  // 获取代理连通性状态
  async getProxyAuthStatus(config: BrowserConfig): Promise<{ authenticated: boolean; message: string }> {
    if (!config.proxy || !config.proxy.enabled) {
      return { authenticated: false, message: '代理未启用' };
    }

    try {
      const result = await this.testProxy(config);
      return {
        authenticated: result.success,
        message: result.message
      };
    } catch (error) {
      return {
        authenticated: false,
        message: `代理连通性检查失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
    }
  }

  // 获取所有配置的代理连通性状态
  // 由于配置现在从API获取，这个方法需要传入配置列表
  async getAllProxyAuthStatuses(configs: BrowserConfig[]): Promise<Map<string, { authenticated: boolean; message: string }>> {
    const statusMap = new Map<string, { authenticated: boolean; message: string }>();
    
    for (const config of configs) {
      if (config.proxy && config.proxy.enabled) {
        const status = await this.getProxyAuthStatus(config);
        statusMap.set(config.id, status);
      } else {
        statusMap.set(config.id, { authenticated: false, message: '代理未启用' });
      }
    }
    
    return statusMap;
  }

  // Cookie 同步相关方法

  /**
   * 从服务器获取并加载 cookie 到浏览器
   */
  private async loadCookiesFromServer(instanceId: string, browser: Browser): Promise<void> {
    try {
      console.log(`Loading cookies from server for instance ${instanceId}`);
      
      // 这里需要调用前端的 API，通过 IPC 传递
      const cookies = await this.getCookiesFromServer(instanceId);
      
      if (cookies && cookies.length > 0) {
        // 保存到本地文件
        const cookieFilePath = CookieManager.getCookieFilePath(instanceId, this.userDataBasePath);
        CookieManager.saveCookiesToFile(cookies, cookieFilePath);
        console.log(`Cookies saved to local file: ${cookieFilePath}`);
        
        // 导入到浏览器
        const success = await CookieManager.importCookies(browser, cookies);
        if (success) {
          console.log(`Successfully imported ${cookies.length} cookies to browser ${instanceId}`);
          
          // 初始化 lastReportedCookies，避免启动时覆盖
          const cookiesJson = JSON.stringify(cookies);
          this.lastReportedCookies.set(instanceId, cookiesJson);
          console.log(`[Cookie Monitor] Initialized lastReportedCookies for instance ${instanceId}`);
        } else {
          console.warn(`Failed to import cookies to browser ${instanceId}`);
        }
      } else {
        console.log(`No cookies found for instance ${instanceId}`);
        // 初始化空的 lastReportedCookies
        this.lastReportedCookies.set(instanceId, '[]');
        console.log(`[Cookie Monitor] Initialized empty lastReportedCookies for instance ${instanceId}`);
      }
    } catch (error) {
      console.error(`Failed to load cookies from server for instance ${instanceId}:`, error);
      // 即使出错也要初始化 lastReportedCookies
      this.lastReportedCookies.set(instanceId, '[]');
      console.log(`[Cookie Monitor] Initialized empty lastReportedCookies for instance ${instanceId} (after error)`);
    }
  }

  /**
   * 从服务器获取 cookie
   */
  private async getCookiesFromServer(instanceId: string): Promise<Cookie[]> {
    try {
      console.log(`Getting cookies from server for instance ${instanceId}`);
      
      const response = await apiClient.getBrowserCookie(instanceId);
      
      if (response.cookie) {
        try {
          const cookies = JSON.parse(response.cookie);
          if (Array.isArray(cookies)) {
            console.log(`Successfully loaded ${cookies.length} cookies for instance ${instanceId}`);
            return cookies;
          } else {
            console.warn(`Invalid cookie format for instance ${instanceId}`);
            return [];
          }
        } catch (parseError) {
          console.error(`Failed to parse cookies for instance ${instanceId}:`, parseError);
          return [];
        }
      } else {
        console.log(`No cookies found for instance ${instanceId}`);
        return [];
      }
    } catch (error) {
      console.error(`Failed to get cookies from server for instance ${instanceId}:`, error);
      return [];
    }
  }

  /**
   * 开始监控 cookie 变化
   */
  private startCookieMonitoring(instanceId: string, browser: Browser): void {
    console.log(`[Cookie Monitor] Starting cookie monitoring for instance ${instanceId}`);
    
    // 清除现有的监控
    this.stopCookieMonitoring(instanceId);
    
    // 延迟启动监控，避免启动时立即覆盖服务器上的 cookie
    setTimeout(() => {
      console.log(`[Cookie Monitor] Delayed monitoring start for instance ${instanceId}`);
      
      // 创建新的监控间隔
      const interval = setInterval(async () => {
        try {
          console.log(`[Cookie Monitor] Timer triggered for instance ${instanceId}`);
          await this.checkAndReportCookieChanges(instanceId, browser);
        } catch (error) {
          console.error(`[Cookie Monitor] Error in monitoring for instance ${instanceId}:`, error);
        }
      }, this.COOKIE_MONITOR_INTERVAL);
      
      this.cookieMonitorIntervals.set(instanceId, interval);
      console.log(`[Cookie Monitor] Cookie monitoring started for instance ${instanceId}, interval: ${this.COOKIE_MONITOR_INTERVAL}ms`);
    }, this.COOKIE_MONITOR_DELAY);
    
    console.log(`[Cookie Monitor] Cookie monitoring scheduled for instance ${instanceId}, will start in ${this.COOKIE_MONITOR_DELAY}ms`);
  }

  /**
   * 停止监控 cookie 变化
   */
  private stopCookieMonitoring(instanceId: string): void {
    const interval = this.cookieMonitorIntervals.get(instanceId);
    if (interval) {
      clearInterval(interval);
      this.cookieMonitorIntervals.delete(instanceId);
      this.lastReportedCookies.delete(instanceId);
      console.log(`Stopped cookie monitoring for instance ${instanceId}`);
    }
  }

  /**
   * 检查并报告 cookie 变化
   */
  private async checkAndReportCookieChanges(instanceId: string, browser: Browser): Promise<void> {
    try {
      console.log(`[Cookie Monitor] Checking cookies for instance ${instanceId}`);
      
      // 导出当前 cookies
      const cookies = await CookieManager.exportCookies(browser, instanceId);
      const cookiesJson = JSON.stringify(cookies);
      
      console.log(`[Cookie Monitor] Exported ${cookies.length} cookies for instance ${instanceId}`);
      
      // 检查是否有变化
      const lastReported = this.lastReportedCookies.get(instanceId);
      if (lastReported !== cookiesJson) {
        // 避免报告空的 cookie 状态，除非之前有 cookie
        if (cookies.length === 0 && !lastReported) {
          console.log(`[Cookie Monitor] Skipping empty cookie report for instance ${instanceId} (no previous cookies)`);
          return;
        }
        
        // 避免用空 cookie 覆盖服务器上的有效 cookie
        if (cookies.length === 0 && lastReported && lastReported !== '[]') {
          console.log(`[Cookie Monitor] Skipping empty cookie report for instance ${instanceId} (would overwrite existing cookies)`);
          return;
        }
        
        console.log(`[Cookie Monitor] Cookie changes detected for instance ${instanceId}, reporting to server`);
        
        // 保存到本地文件
        const cookieFilePath = CookieManager.getCookieFilePath(instanceId, this.userDataBasePath);
        CookieManager.saveCookiesToFile(cookies, cookieFilePath);
        
        // 报告到服务器
        await this.reportCookiesToServer(instanceId, cookiesJson);
        
        // 更新最后报告的 cookie
        this.lastReportedCookies.set(instanceId, cookiesJson);
      } else {
        console.log(`[Cookie Monitor] No cookie changes for instance ${instanceId}`);
      }
    } catch (error) {
      console.error(`[Cookie Monitor] Failed to check cookie changes for instance ${instanceId}:`, error);
    }
  }

  /**
   * 报告 cookies 到服务器
   */
  private async reportCookiesToServer(instanceId: string, cookiesJson: string): Promise<void> {
    try {
      console.log(`Reporting cookies to server for instance ${instanceId}`);
      
      const success = await apiClient.reportCookie(instanceId, cookiesJson);
      
      if (success) {
        console.log(`Successfully reported cookies for instance ${instanceId}`);
      } else {
        console.warn(`Failed to report cookies for instance ${instanceId}`);
      }
    } catch (error) {
      console.error(`Failed to report cookies to server for instance ${instanceId}:`, error);
    }
  }

  /**
   * 清理所有 cookie 监控
   */
  private cleanupAllCookieMonitoring(): void {
    for (const [instanceId] of this.cookieMonitorIntervals) {
      this.stopCookieMonitoring(instanceId);
    }
  }

  /**
   * 调试方法：获取 cookie 监控状态
   */
  getCookieMonitoringStatus(): { [key: string]: { isMonitoring: boolean; lastReported: string | null } } {
    const status: { [key: string]: { isMonitoring: boolean; lastReported: string | null } } = {};
    
    for (const [instanceId, interval] of this.cookieMonitorIntervals) {
      status[instanceId] = {
        isMonitoring: !!interval,
        lastReported: this.lastReportedCookies.get(instanceId) || null
      };
    }
    
    return status;
  }

  // 在 BrowserManager 类中添加自动化方法
  async autoGoogleSearch(browser: Browser, keyword: string, domain: string) {
    const page = (await browser.pages())[0] || await browser.newPage();
    await injectFingerprintScripts(page);
    await page.bringToFront();
    await page.goto('https://www.google.com', { waitUntil: 'domcontentloaded' });

    // 行为模拟：随机鼠标移动、滚动
    await page.mouse.move(100 + Math.random() * 200, 200 + Math.random() * 100, { steps: 10 });
    await page.waitForTimeout(300 + Math.random() * 300);
    await page.mouse.move(300 + Math.random() * 200, 400 + Math.random() * 100, { steps: 10 });
    await page.waitForTimeout(300 + Math.random() * 300);
    await page.evaluate(() => window.scrollBy(0, Math.random() * 200));
    await page.waitForTimeout(300 + Math.random() * 300);

    // 处理“同意”弹窗（主页面和iframe）
    try {
      const agreeBtn = await page.$x("//button[contains(., '同意') or contains(., 'Accept all') or contains(., 'I agree')]") as unknown as ElementHandle<Element>[];
      if (agreeBtn.length > 0) {
        await agreeBtn[0].hover();
        await page.waitForTimeout(200 + Math.random() * 200);
        await agreeBtn[0].click();
        await page.waitForTimeout(1000);
      } else {
        // 检查iframe
        const frames = page.frames();
        for (const frame of frames) {
          const agreeBtnInFrame = await frame.$x("//button[contains(., '同意') or contains(., 'Accept all') or contains(., 'I agree')]") as unknown as ElementHandle<Element>[];
          if (agreeBtnInFrame.length > 0) {
            await agreeBtnInFrame[0].hover();
            await page.waitForTimeout(200 + Math.random() * 200);
            await agreeBtnInFrame[0].click();
            await page.waitForTimeout(1000);
            break;
          }
        }
      }
    } catch (e) {}

    // 查找输入框（textarea优先，找不到再找input）
    let inputHandle: ElementHandle<Element> | null = null;
    for (let i = 0; i < 5; i++) {
      inputHandle = await page.$('textarea.gLFyf[name="q"]');
      if (!inputHandle) inputHandle = await page.$('input[name="q"]');
      if (inputHandle) break;
      await page.waitForTimeout(1000);
    }
    if (!inputHandle) throw new Error('Google搜索框不可用');

    // 行为模拟：点击输入框
    await inputHandle.hover();
    await page.waitForTimeout(200 + Math.random() * 200);
    await inputHandle.click({ clickCount: 1, delay: 100 + Math.random() * 100 });
    await page.waitForTimeout(200 + Math.random() * 200);

    // 清空输入框再输入
    await page.evaluate((el: Element) => { (el as HTMLInputElement | HTMLTextAreaElement).value = ''; }, inputHandle);
    // 行为模拟：逐字输入关键词
    for (const char of keyword) {
      await inputHandle.type(char, { delay: 80 + Math.random() * 40 });
    }
    await page.waitForTimeout(500 + Math.random() * 500);
    await page.keyboard.press('Enter');
    await page.waitForNavigation({ waitUntil: 'domcontentloaded' });

    // 行为模拟：滚动页面
    await page.evaluate(() => window.scrollBy(0, Math.random() * 400));
    await page.waitForTimeout(500 + Math.random() * 500);

    let found = false;
    for (let i = 0; i < 10; i++) {
      const links: string[] = await page.$$eval('a', (as: HTMLAnchorElement[]) => as.map((a: HTMLAnchorElement) => a.href));
      const target = links.find((href: string) => href.includes(domain));
      if (target) {
        await page.evaluate((url: string) => { window.location.href = url; }, target);
        found = true;
        break;
      }
      const nextBtn = await page.$('a#pnnext, a[aria-label="Next page"], a[aria-label="下一页"]');
      if (nextBtn) {
        await nextBtn.hover();
        await page.waitForTimeout(200 + Math.random() * 200);
        await nextBtn.click();
        await page.waitForNavigation({ waitUntil: 'domcontentloaded' });
        await page.evaluate(() => window.scrollBy(0, Math.random() * 400));
        await page.waitForTimeout(500 + Math.random() * 500);
      } else {
        break;
      }
    }
    return found;
  }
}

// 注入指纹伪装脚本函数，放在autoGoogleSearch前
async function injectFingerprintScripts(page: import('puppeteer-core').Page) {
  // Canvas指纹伪装
  await page.evaluateOnNewDocument(() => {
    const toDataURL = HTMLCanvasElement.prototype.toDataURL;
    HTMLCanvasElement.prototype.toDataURL = function(...args) {
      const context = this.getContext('2d');
      if (context) {
        context.fillStyle = 'rgba(100,100,100,0.1)';
        context.fillRect(0, 0, 10, 10);
      }
      return toDataURL.apply(this, args);
    };
  });
  // WebGL指纹伪装
  await page.evaluateOnNewDocument(() => {
    const getParameter = WebGLRenderingContext.prototype.getParameter;
    WebGLRenderingContext.prototype.getParameter = function(parameter) {
      if (parameter === 37445) return 'Intel Inc.';
      if (parameter === 37446) return 'Intel Iris OpenGL Engine';
      return getParameter.call(this, parameter);
    };
  });
  // Audio指纹伪装
  await page.evaluateOnNewDocument(() => {
    const getChannelData = AudioBuffer.prototype.getChannelData;
    AudioBuffer.prototype.getChannelData = function(channel: number) {
      const data = getChannelData.call(this, channel);
      for (let i = 0; i < data.length; i += 100) {
        data[i] = data[i] + Math.random() * 0.0000001;
      }
      return data;
    };
  });
  // navigator属性伪装
  await page.evaluateOnNewDocument(() => {
    Object.defineProperty(navigator, 'languages', { get: () => ['zh-CN', 'zh', 'en'] });
    Object.defineProperty(navigator, 'platform', { get: () => 'Win32' });
    Object.defineProperty(navigator, 'hardwareConcurrency', { get: () => 8 });
    Object.defineProperty(navigator, 'deviceMemory', { get: () => 8 });
  });
}

export const browserManager = new BrowserManager();

// Event handlers
process.on('exit', () => browserManager.stopAllBrowsers());
process.on('SIGINT', () => browserManager.stopAllBrowsers().then(() => process.exit(0)));
process.on('SIGTERM', () => browserManager.stopAllBrowsers().then(() => process.exit(0))); 